package com.gitee.ting723.upload.service;


import com.gitee.ting723.upload.FileUtil;
import com.gitee.ting723.upload.config.FileUploadConfig;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 图片服务
 *
 * @author zhanglianwei
 */
@Service
public class ImageService {

    @Resource
    private FileUploadConfig fileUploadConfig;

    /**
     * 保存图片
     *
     * @param file file
     * @return String
     */
    @SneakyThrows
    public String saveImage(MultipartFile file) {
        // 文件全路径
        String filename = FileUtil.createFileName(fileUploadConfig.getDir(), file);
        FileUtil.writeFileToLocal(file, filename);
        return fileUploadConfig.getDomain() + FileUtil.getUrlName(filename, fileUploadConfig.getDir());
    }

    /**
     * 批量保存图片
     * @param fileList fileList
     * @return List
     */
    public List<String> saveImages(List<MultipartFile> fileList) {
        return fileList.stream().map(this::saveImage).collect(Collectors.toList());
    }
}
